﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using FwProject.Authorization.Users;
using FwProject.Com.Dto;
using FwProject.ShopApplication;
using FwProject.ShoppingMall.Com;
using X.PagedList;

namespace FwProject.Com
{
    
    public class SettlementSupplierAppService : FwProjectAppServiceBase, ISettlementSupplierAppService
    {
        private readonly IRepository<SettlementSupplier, Guid> _repositorySettlementSupplier;
        private readonly IRepository<ShopSupplier, Guid> _repositoryShopSupplier;
        private readonly IRepository<User, long> _repositoryUser;
        private readonly IRepository<ShopOrderDetails, Guid> _repositoryShopOrderDetails;
        private IGuidGenerator _guid { get; set; }
        public IObjectMapper _map { get; set; }

        public SettlementSupplierAppService(IRepository<SettlementSupplier, Guid> repositorySettlementSupplier, IRepository<ShopSupplier, Guid> repositoryShopSupplier,
            IRepository<User, long> repositoryUser, IRepository<ShopOrderDetails, Guid> repositoryShopOrderDetails)
        {
            _repositorySettlementSupplier = repositorySettlementSupplier;
            _repositoryShopSupplier = repositoryShopSupplier;
            _repositoryUser = repositoryUser;
            _repositoryShopOrderDetails = repositoryShopOrderDetails;
            _map = NullObjectMapper.Instance;
            _guid = SequentialGuidGenerator.Instance;
        }

        public async Task<Guid> Create(SettlementSupplierInput input)
        {
            var model = _map.Map<SettlementSupplier>(input);
            model.Id = _guid.Create();
            return await _repositorySettlementSupplier.InsertAndGetIdAsync(model);
        }
        /// <summary>
        /// 创建一条结算数据并修改订单明细表结算状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task EditSettlementStatus(SettlementSupplierEnterDto input)
        {
            var user = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            SettlementSupplierInput sinput = new SettlementSupplierInput()
            {
                SupplierId = input.SupplierId,
                SettlementPrice = input.SettlementPrice,
                SettlementPreferentia = input.SettlementPreferentia,
                SettlementAmount = input.SettlementAmount,
                SettlementTime = DateTime.Now,
                SettlementId = user.Id
            };
            var model = _map.Map<SettlementSupplier>(sinput);
            var id = _guid.Create();
            model.Id = id;
            await _repositorySettlementSupplier.InsertAndGetIdAsync(model);

            string[] arry = input.Str.Split("|");
            int i = 0;
            foreach (var item in arry)
            {
                if (i == arry.Count() - 1)
                {
                    break;
                }
                Guid orderDetailsId = new Guid(item);
                var detail = await _repositoryShopOrderDetails.GetAsync(orderDetailsId);
                detail.SettlementId = model.Id;
                detail.SettlementStatus = SettlementStatus.已结算;
                detail.SettlementTime = DateTime.Now;
                await _repositoryShopOrderDetails.UpdateAsync(detail);
                i++;
            }
        }
        /// <summary>
        /// 修改审核状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task EditExamineStatus(Guid id)
        {
            var model = await _repositorySettlementSupplier.GetAsync(id);
            model.ExamineStatus = ExamineStatus.已审核;
            await _repositorySettlementSupplier.UpdateAsync(model);
        }
        /// <summary>
        /// 获取结算单列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<LayerDataBaseDto> GetSupplierSettlementAsync(int page, int limit, string supplierName, string settlementTime, string examineStatus)
        {
            var model = _repositorySettlementSupplier.GetAll();

            var suppiler = _repositoryShopSupplier.GetAll();
            var data = model.Join(suppiler, a => a.SupplierId, b => b.Id, (a, b) => new SupplierSettlementOutput
            {
                Id = a.Id,
                ExamineStatus = a.ExamineStatus,
                SupplierName = b.SupplierName,
                SettlementTime = a.SettlementTime,
                SettlementAmount = a.SettlementAmount,
                SettlementPreferentia = a.SettlementPreferentia,
                SettlementPrice = a.SettlementPrice,
                SettlementUser = _repositoryUser.Get(a.SettlementId).Name
            }).OrderByDescending(o => o.SettlementTime);

            if (!string.IsNullOrEmpty(supplierName))
                data = data.Where(o => o.SupplierName == supplierName).OrderByDescending(o => o.SettlementTime);

            if (!string.IsNullOrEmpty(settlementTime))
            {
                DateTime beginTime = new DateTime();
                DateTime endTime = new DateTime();
                var time = settlementTime.Split('~');

                if (time.Count() == 2)
                {
                    beginTime = Convert.ToDateTime(time[0].Trim());
                    endTime = Convert.ToDateTime(time[1].Trim());
                }
                data = data.Where(o => o.SettlementTime >= beginTime && o.SettlementTime <= endTime.AddHours(24)).OrderByDescending(o => o.SettlementTime);
            }

            if (examineStatus == "0")
                data = data.Where(o => o.ExamineStatus == ExamineStatus.未审核).OrderByDescending(o => o.SettlementTime);
            if (examineStatus == "1")
                data = data.Where(o => o.ExamineStatus == ExamineStatus.已审核).OrderByDescending(o => o.SettlementTime);

            var datalist = await data.OrderBy(o => o.ExamineStatus).ToPagedListAsync(page, limit);

            LayerDataBaseDto dto = new LayerDataBaseDto();
            dto.Data = datalist;
            dto.Count = datalist.TotalItemCount;
            return dto;
        }
        /// <summary>
        /// 结算单导出
        /// </summary>
        /// <param name="supplierName"></param>
        /// <param name="settlementTime"></param>
        /// <returns></returns>
        public async Task<List<SupplierSettlementOutput>> GetExportSupplierSettlementAsync(string supplierName, string settlementTime)
        {
            var model = _repositorySettlementSupplier.GetAll();

            var suppiler = _repositoryShopSupplier.GetAll();
            var data = model.Join(suppiler, a => a.SupplierId, b => b.Id, (a, b) => new SupplierSettlementOutput
            {
                Id = a.Id,
                SupplierName = b.SupplierName,
                SettlementTime = a.SettlementTime,
                SettlementAmount = a.SettlementAmount,
                SettlementPreferentia = a.SettlementPreferentia,
                SettlementPrice = a.SettlementPrice,
                SettlementUser = _repositoryUser.Get(a.SettlementId).Name
            });

            if (!string.IsNullOrEmpty(supplierName))
                data = data.Where(o => o.SupplierName == supplierName);

            if (!string.IsNullOrEmpty(settlementTime))
            {
                DateTime beginTime = new DateTime();
                DateTime endTime = new DateTime();
                var time = settlementTime.Split('~');

                if (time.Count() == 2)
                {
                    beginTime = Convert.ToDateTime(time[0].Trim());
                    endTime = Convert.ToDateTime(time[1].Trim());
                }
                data = data.Where(o => o.SettlementTime >= beginTime && o.SettlementTime <= endTime.AddHours(24));
            }
            return await data.OrderByDescending(o => o.SettlementTime).ToListAsync();
        }
    }
}
